package com.gpframework.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.extern.slf4j.Slf4j;

/**
 * json 工具类
 *
 * @author BrinedFish
 * @create 2022-06-16 0:06
 */
@Slf4j
public class JsonUtils {

    /**
     * 序列化对象为字符串
     * - 不序列化空字段。
     * - Long 序列化为字符串。
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String toJSONString(T t) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            SimpleModule simpleModule = new SimpleModule();
            simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
            simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
            objectMapper.registerModule(simpleModule);
            return objectMapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            return null;
        }
    }

}
